package com.crl.net.loader
{
	import com.crl.core.crl_internal;
	import com.crl.factory.pool.IPool;
	import com.crl.factory.pool.IRecycleable;
	import com.crl.net.NetStatus;
	import com.crl.net.ResourceToken;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	use namespace crl_internal;
	public class StreamLoader extends URLLoader implements IRecycleable
	{
		private var token:ResourceToken;
		private var pool:IPool;
		public function StreamLoader()
		{
			super();
			dataFormat=URLLoaderDataFormat.BINARY;
			
			this.addEventListener(Event.COMPLETE,compleHandler);
			this.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			this.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
		}
		
		public function loadPath(path:String):void{
			var request:URLRequest=new URLRequest(path);
			load(request);
			token._status=NetStatus.LOADING;
		}
		
		public function bindToken(token:ResourceToken):void{
			this.token=token;
			this.token._stopHandler=stopHandler;
			this.token._status=NetStatus.NONE;
		}
		
		protected function compleHandler(event:Event):void{
			token.dispatchSuccessed(data);
			token._status=NetStatus.COMPLETE;
			
			recycle();
		}
		protected function errorHandler(event:IOErrorEvent):void{
			token.dispatchFailed(event);
			token._status=NetStatus.FAILED;
			
			recycle();
		}
		
		protected function progressHandler(event:ProgressEvent):void{
			token.dispatchProgress(event);
		}
		
		/**
		 * 停止加载 
		 * @param type
		 * 
		 */		
		protected function stopHandler(type:int):void{
			try{
				this.close();
			}catch(e:Error){
				
			}
			
			token._status=NetStatus.FAILED;
			
			recycle();
		}
		
		public function dispose():void{
			token=null;
		}
		
		public function awake():void
		{	
		}
		
		public function sleep():void{
		}
		
		public function recycle():void
		{
			token._stopHandler=null;
			token=null;
			
			if(pool){
				pool.recycle(this);
			}else{
				this.dispose();
			}
		}
		
		public function setPool(pool:IPool):void
		{
			this.pool=pool;
		}
		
	}
}